<template>
    <isLoginOk v-if="!isLogin" />
    <tabbar />
    <u-dropdown>
        <u-dropdown-item v-model="state.value" title="类型" :options="state.selectOptions"></u-dropdown-item>
    </u-dropdown>
    <view style="width: 700rpx;margin: 0 auto;display: flex">
        <view style="background-color: #fff;padding: 20rpx;border-radius: 10rpx;">
            {{type}}
<!--            <pop-selector v-if="state.selectOptions.length" :select-options="state.selectOptions"-->
<!--                          :default-value="state.value" @changeSelect="onChangeMenu">-->
<!--                <view>-->
<!--                    状态选择：{{ state.selectOptions[state.value]?.label }}-->
<!--                </view>-->
<!--            </pop-selector>-->
            <!--        <u-icon name="arrow-leftward" color="#f56c6c" size="12"></u-icon>-->
  
        </view>
        <view style="background-color: #fff;margin-left: 10rpx">
            <u-input
                ref="input"
                border="surround"
                :focus="domFocus"
                v-model="state.orderNumber"
                @confirm="onConfirm"
                placeholder="请点击然后录入"></u-input>

        </view>

    </view>

    <view style="width: 700rpx;margin: 60rpx  auto 0;">

        <text style="font-size: 40rpx;font-weight: bold">当前扫码</text>
        <view v-if="state.nowData.order_number"
              style="width: 700rpx;margin: 10rpx  auto 0;padding: 20rpx; border-radius: 10rpx; box-shadow: 5rpx 5rpx 10rpx rgba(0, 0, 0, 0.5);">
            <view style="margin-top: 20rpx">
                <view style="display: inline-flex;width: 200rpx">单号</view>
                <text>{{ state.nowData.order_number }}</text>
            </view>
            <view style="margin-top: 20rpx">
                <view style="display: inline-flex;width: 200rpx">次数</view>
                <text>{{ state.nowData.count }}</text>
            </view>
            <view style="margin-top: 20rpx">
                <view style="display: inline-flex;width: 200rpx">录入时间</view>
                <text>{{ state.nowData.timestamp }}</text>
            </view>
            <view style="margin-top: 20rpx">
                <view style="display: inline-flex;width: 200rpx">录入人</view>
                <text>{{ userInfo?.real_name }}</text>
            </view>
            <view style="margin-top: 20rpx">
                <view style="display: inline-flex;width: 200rpx">状态</view>
                <text :style="{color:state.nowData.status === '正常'?'green':'red'}">{{ state.nowData.status }}</text>
            </view>
            <errDetail :order_number="state.nowData.order_number" v-if="state.nowData.status === '异常'" />
        </view>
        <view v-else style="text-align: center;margin-top: 20rpx">待扫码</view>

        <view style="display: flex;margin-top: 20rpx">
            <u-input
                v-model="password"
                type="password"
                placeholder="请输入清空验证密码"></u-input>
            <!--        清空-->
            <u-button type="primary" shape="round" @click="toEmpty">清空{{number}}</u-button>

        </view>
<!--        {{JSON.stringify(codeList)}}-->
        <view v-for="item in codeList">单号：{{item.order_number}}</view>
    </view>

</template>

<script setup lang="ts">
import { getDecorate } from '@/api/shop'
import { useUserStore } from '@/stores/user'
import { onShow } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { computed, nextTick, reactive, ref, watch } from 'vue'
import isLoginOk from '@/components/isLogin/index.vue'
import popSelector from '@/uni_modules/wo-pop-selector/components/wo-pop-selector/wo-pop-selector.vue'
import { checkPassword, getCategory, getRecordByOrderNumber, record } from '@/api/code'
import errDetail from '@/components/err-Detail/index.vue'
// test()
const number = ref(0)

// const onChangeMenu = (data: any) => {
//     console.log(data, 'data')
//
//     //查找当前的下标
//     const index = state.selectOptions.findIndex((item: any) => item.value === data.value)
//     console.log(index, 'index')
//     state.value = index
//     state.category_id = data.value
// }
const state = reactive<{
    meta: any[]
    pages: any[],
    selectOptions: any[],
    value: number,
    orderNumber: string,
    category_id: number,
    nowData: Object
}>({
    meta: [],
    pages: [],
    value: 0,
    selectOptions: [],
    orderNumber: '',
    category_id: 0,
    nowData: {}
})

//计算出对应的type
const type = computed(() => {
    let type = '未选择';

    state.selectOptions.forEach((item: any) => {
        if (item.value === state.value) {
            type = item.label
        }
    })


    return type
})

//监听state.value的变化
watch(() => state.value, (value) => {
    console.log(value, 'value')
    //缓存
    uni.setStorageSync('category_id', value)
})

//拿到缓存中的category_id
if (uni.getStorageSync('category_id')) {
    state.value = uni.getStorageSync('category_id')
}




const password = ref('')
const toEmpty = async () => {
    const res = await checkPassword({
        password: password.value
    })
    console.log(res,'res')
    if (res?.isOk){
        number.value = 0
        codeList.value = []
        uni.setStorageSync('codeList', codeList.value)
        uni.setStorageSync('number', number.value)
    }

}


const domFocus = ref<any>(false)

const codeList = ref<any>([])

//判断缓存中的数据是否存在codeList
if (uni.getStorageSync('codeList')) {
    codeList.value = uni.getStorageSync('codeList')
}
if (uni.getStorageSync('number')) {
    number.value = uni.getStorageSync('number')
}

// const input = ref<any>()
// vibrate：震动
// othre：铃声
const msg_remind = function(type: string) {
    console.log(type)
    // if (type == 'vibrate') {
    //     //震动
    //     plus.device.vibrate(500)
    // } else {
    //     //声音
    //     let main = plus.android.runtimeMainActivity()
    //     let RingtoneManager = plus.android.importClass('android.media.RingtoneManager')
    //     let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION)
    //     let MediaPlayer = plus.android.importClass('android.media.MediaPlayer')
    //     let player = MediaPlayer.create(main, uri)
    //     player.setLooping(false)
    //     player.prepare()
    //     player.start()
    // }
    //播放本地声音
    const audio = uni.createInnerAudioContext()

    if (type == 'vibrate') {
        audio.src = '/static/mp3/error.mp3'
    } else {
        audio.src = '/static/mp3/di.mp3'
    }
    audio.play()

}

// 异常详情
// const errorDetail = reactive({
//     show: false,
//     list: [{
//         'id': 20,
//         'timestamp': '2024-08-07 00:36:48',
//         'user_id': 1,
//         'count': 1,
//         'order_number': '111',
//         'category_id': 1,
//         'status': '正常',
//         'delete_time': null
//     }],
//     close() {
//         errorDetail.show = false
//     },
//     open() {
//         errorDetail.show = true
//     }
// })
// const lookDetail = () => {
//     errorDetail.show = true
//     getRecordByOrderNumber(state.nowData.order_number).then((res) => {
//         console.log(res, 'res')
//         errorDetail.list = res
//     })
//     console.log('查看详情')
// }

const onConfirm = async (value: string) => {
    console.log(value, 'value111')
    domFocus.value = false
	//清空并且光标
	state.orderNumber = ''
    state.nowData = await record({
        order_number: value,
        category_id: state.value
    })
    console.log('100')
    //把state.nowData缓存起来
    uni.setStorageSync('nowData', state.nowData)
    console.log('100')



    await nextTick(() => {
        domFocus.value = true
        // input.value.focus()
    })
    console.log('100')
    uni.hideKeyboard()// 隐藏键盘
    console.log('全部');
    if (state.nowData.status === '正常') {
        console.log('正常');
        // codeList.value.push({
        //     order_number: state.nowData.order_number,
        // })
        //往前面新增
        codeList.value.unshift({
            order_number: state.nowData.order_number,
        })
        number.value++
        uni.setStorageSync('codeList', codeList.value)
        uni.setStorageSync('number', number.value)
        msg_remind('othre')
    } else {
        console.log('异常');
        msg_remind('vibrate')
    }

}
state.nowData = uni.getStorageSync('nowData') || {}


const getCategoryData = async (isOk: any = false) => {
    state.selectOptions = await getCategory()
}


const getData = async () => {
    const data = await getDecorate({ id: 2 })
    state.meta = JSON.parse(data.meta)
    state.pages = JSON.parse(data.data)
    uni.setNavigationBarTitle({
        title: state.meta[0].content.title
    })
}
const userStore = useUserStore()
const { userInfo, isLogin } = storeToRefs(userStore)
onShow(() => {
    userStore.getUser()
    getCategoryData(true)
})
getData()
</script>

<style lang="scss" scoped>

</style>
